#coding:utf-8
from glob import glob
import argparse
import os
import codecs
import logging

"""原始文件中的位置信息分散在txt中，且带有中文，这个脚本把原始文件中的位置信息整合在txt中"""
"""整合格式：图片路径、左上角坐标、右下角坐标、宽度、高度"""


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('img_path', help='path to all the images')
    parser.add_argument('-o', '--output', default="output.txt", help='output file name')
    parser.add_argument('-f', '--format', default="jpg", help='image format')
    return parser.parse_args()

def work(args):
    pattern = os.path.join(args.img_path, '*.{}'.format(args.format.strip()))
    pics = glob(pattern)
    logging.info('Looking for: ' + pattern)
    count = 0
    with open(args.output, 'w') as output:
        for pic in pics:
            txt = os.path.join(os.path.dirname(pic), os.path.basename(pic)[0:-4] + '.txt')
            with codecs.open(txt, encoding='CP936') as f:
                width = f.readline().split(':')[1]
                height = f.readline().split(':')[1]
                [f.readline() for i in range(3)]
                left_up = f.readline().split(':')[1]
                f.readline()
                right_down = f.readline().split(':')[1]
                output.write(pic.strip() + ' ' + left_up.strip() + ' ' + right_down.strip() + " " + width.strip() + ' ' + height.strip() + '\n')
                count += 1
    logging.info('Finished processing %d file' % count)


def main():
    args = parse_args()
    work(args)



if __name__ == '__main__':
    main()
